from django.db import models

# Create your models here.

class Books(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)
    publisher = models.ForeignKey("Publish", on_delete=models.CASCADE)
    authers = models.ManyToManyField("Auther")

    def get_book_authers(self):
        authers= self.authers.all()
        data_list = []
        if authers:
            for auther in authers:
                data = {"id": auther.id, "name": auther.name}
                data_list.append(data)
        return data_list

    def get_publisher(self):
        publisher = self.publisher
        data = {}
        if publisher:
            data = {"id": publisher.id, "name": publisher.name}
        return data
    
    @property
    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "publisher": self.get_publisher(),
            "authers": self.get_book_authers()
        }

class Publish(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)

    def get_publish_books(self):
        books = self.books_set.all()
        if books:
            return  [{"id":book.id, "name": book.name} for book in books ]
        return []

    @property
    def to_json(self):
        return {
            "id": self.id, 
            "name": self.name,
            "books": self.get_publish_books()
        }

class Auther(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=64)

    def get_auther_books(self):
        books = self.books_set.all()
        if books:
            return  [{"id":book.id, "name": book.name} for book in books ]
        return []

    @property
    def to_json(self):
        return {
            "id": self.id, 
            "name": self.name,
            "books": self.get_auther_books()
        }
